<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Lib\Token;
use Psr\Container\ContainerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class MustMiddleware implements MiddlewareInterface {
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var HttpResponse
     */
    protected $response;

    /**
     * @var Token
     */
    protected $token;

    public function __construct(ContainerInterface $container, HttpResponse $response, Token $token) {
        $this->container = $container;
        $this->response = $response;
        $this->token = $token;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
        $res = Signatrue::check($request);
        if ($res) {
            return $this->response->json(resData(10002, $res, new \stdClass()));
        }
        $token = $this->token->accessTokenVerify($request->getHeaderLine('xx-token'));
        switch ($token) {
            case 'invalid':
                return $this->exit(10009, '登录token无效');
            case 'other':
                return $this->exit(10004, '其他设备登录');
            default:
                $request = $request->withAttribute('uid', $token);
        }
        return $handler->handle(\Hyperf\Utils\Context::set(ServerRequestInterface::class, $request));
    }

    private function exit($code, $msg) {
        return $this->response->json(resData($code, $msg, new \stdClass()));
    }
}
